import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import React from 'react';
import { handleTestDataSourceConnection } from '@/utils/dataSourceUtils';

interface Props {
  visible: boolean;
  onSubmit: (values: DataSourceType.DataSource) => Promise<boolean>;
  onCancel: () => void;
}

/**
 * 创建数据源模态框
 *
 * @param props
 * @constructor
 */
const CreateModal: React.FC<Props> = (props) => {
  const { visible, onSubmit, onCancel } = props;
  const [form] = Form.useForm();

  return (
    <ModalForm<DataSourceType.DataSource>
      title="新建数据源"
      form={form}
      autoFocusFirstInput
      modalProps={{
        onCancel: onCancel,
        destroyOnClose: true,
      }}
      visible={visible}
      onFinish={async (values) => {
        return onSubmit?.(values);
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <Button key="test" type="primary" onClick={() => handleTestDataSourceConnection(form)}>
              测试连接
            </Button>,
            ...defaultDoms,
          ];
        },
      }}
    >
      <ProFormText
        name="name"
        label="名称"
        placeholder="请输入名称"
        rules={[{ required: true, message: '请输入名称' }]}
      />
      <ProFormSelect
        name="type"
        label="类型"
        placeholder="请选择类型"
        options={[
          {
            value: 'mysql',
            label: 'MySQL',
          },
          {
            value: 'oracle',
            label: 'Oracle',
          },
          {
            value: 'postgresql',
            label: 'PostgreSQL',
          },
          {
            value: 'sqlserver',
            label: 'SQL Server',
          },
        ]}
        rules={[{ required: true, message: '请选择类型' }]}
      />
      <ProFormText
        name="url"
        label="连接地址"
        placeholder="请输入连接地址"
        rules={[{ required: true, message: '请输入连接地址' }]}
      />
      <ProFormText
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        rules={[{ required: true, message: '请输入用户名' }]}
      />
      <ProFormText.Password
        name="password"
        label="密码"
        placeholder="请输入密码"
        // 密码可选，因为某些数据库可能不需要密码
      />
    </ModalForm>
  );
};

export default CreateModal;
